#!/usr/bin/perl

require 5.003;
BEGIN { $ENV{PATH} = '/bin' }
use Socket;
use POSIX;

sub usage;

my @server = split (/:/,shift);
my $remote = $server[0] || $ARGV[0];
my $port = $server[1] || 2375;

$pedido = "\x00\x02\xF1\x26\x01\x26\xF0\x90\xA6\xF0\x26\x57\x4E\xAC\xA0\xEC\xF8\x68\xE4\x8D\x21";

my $remoteaddr = inet_aton("$remote");
my $paddr = sockaddr_in($port, $remoteaddr) || die "Can't create info for connection: #!\n";;
my $proto = getprotobyname('udp');
socket(Server, PF_INET, SOCK_DGRAM, $proto) || die "Can't create socket: $!";

send(Server, $pedido, 0, $paddr) or die "send: $!";

$rin = "";
vec($rin, fileno(Server), 1) = 1;
select($rout = $rin, undef, undef, 3.0) or die "No response\n";

$paddr = recv(Server, $serveranswer, 90, 0)      or die "recv: $!";

$maximo = ord(substr($serveranswer,20,1)) -1 ;
$jogando = ord(substr($serveranswer,24,1)) -1 ;
print "Now playing: $jogando / $maximo\n";
exit;

sub usage {
	print "Minimum arguments not supplied!\n";
	print "\n";
	print "Check Freelancer server capacity\n";
	print "\n";
	print "Usage: $0 <host>[:<port>] \n";
	print "\n";
        print "<host> = remote host.\n";
	print "<port> = Port that the freelancer server is running on <host>.\n	Defaults to 2375.\n";
	exit;
}
